package com.hxzy.tms.action;

import java.io.IOException;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.WebUtils;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

public abstract class AbstractAction extends ActionSupport {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final long serialVersionUID = 2900126534347830365L;

    protected boolean isGET() {
        return "GET".equals(ServletActionContext.getRequest().getMethod());
    }

    protected boolean isPOST() {
        return "POST".equals(ServletActionContext.getRequest().getMethod());
    }

    protected String ipv4() {
        return ServletActionContext.getRequest().getRemoteAddr();
    }

    protected void writeJson(Object data) {
        ServletActionContext.getResponse().setCharacterEncoding("utf-8");
        ServletActionContext.getResponse().setContentType("application/json");

        try {
            Gson gson = new Gson();
            ServletActionContext.getResponse().getWriter().println(gson.toJson(data));
        } catch (IOException e) {
            logger.error("向客户端写入 json 字符串", e);
        }
    }

    protected void addCookie(Cookie cookie) {
        ServletActionContext.getResponse().addCookie(cookie);
    }

    protected String getCookie(String key) {
        Cookie c = WebUtils.getCookie(ServletActionContext.getRequest(), key);
        return c != null ? c.getValue() : null;
    }
}
